//
//  saveSandBox.m
//  FCPackage
//
//  Created by WJC on 2018/11/2.
//  Copyright © 2018 wjc. All rights reserved.
//

#import "saveSandBox.h"
#import "NSObject+KVCChangeType.h"
#import "NSDictionary+setDic.h"
#import <sqlite3.h>
#define SQLNAME @"fuCheng.sqlite"
#define SQLNAMEList @"fuChengList.sqlite"
#define SQLNAMEH5 @"fuChengH5.sqlite"
#import "WJCDefine.h"
#import "MJExtension.h"
#import <Security/Security.h>
#import "MJExtension.h"

@implementation saveSandBox
+(void)saveJSLocalWithData:(NSURL *)jsurl andurlName:(NSString *)urlName andVersion:(NSString *)version{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *testDirPath = [documentsPath stringByAppendingPathComponent:@"js"];
    NSFileManager *fileMgr = [NSFileManager defaultManager];
//    NSData *urlData = [NSData dataWithContentsOfURL:jsurl];
//    [urlData writeToFile:documentsPath atomically:YES];
    NSError *error = nil;
    if(![fileMgr createDirectoryAtPath:testDirPath withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"创建文件夹失败:%@", error.userInfo);
    }
//    NSString *firstFilePath = [testDirPath stringByAppendingPathComponent:version];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:jsurl];
            request.timeoutInterval = 20.0;
            request.HTTPMethod = @"POST";
            NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                if (!location) {
                    return ;
                }
        
                    // 文件移动到documnet路径中
                NSError *saveError;
                NSURL *saveURL = [NSURL fileURLWithPath:[testDirPath stringByAppendingPathComponent:version]];
                [[NSFileManager defaultManager] moveItemAtURL:location toURL:saveURL error:&saveError];
                NSLog(@"%@",saveError);
            }];
            [downLoadTask resume];
//    [fileMgr createFileAtPath:firstFilePath contents:urlData attributes:nil];
   
    
//            NSString *saveName=[NSString stringWithFormat:@"js/%@",version];
//            if (saveName) {
//                documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
//            }

    
//    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//    NSString *saveName=[NSString stringWithFormat:@"%@/%@",urlName,version];
//    if (saveName) {
//        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
//    }
//    [jsdata writeToFile:documentsPath atomically:YES];
//    [jsdata writeToFile:documentsPath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}
+(NSData*)getJSLocalWithUrlName:(NSString *)urlName andVersion:(NSString *)version{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *testDirPath = [documentsPath stringByAppendingPathComponent:@"js"];
//    if (version&&urlName) {
//        NSString *saveName=[NSString stringWithFormat:@"%@",version];
//        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
//
        NSData *data=[NSData dataWithContentsOfFile:testDirPath];
        if (data.length>0) {
            return data;
        }
//    }
    return nil;
}
+(void)saveLocalWithClass:(Class)saveClass andObject:(id)object{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=NSStringFromClass(saveClass);
    NSString *saveStr=[NSString new];
    if (saveName) {
        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    }
    if ([object isKindOfClass:[NSArray class]]) {
        NSMutableArray *arr=[NSMutableArray new];
        for (id d in object) {
            if ([d isKindOfClass:[NSDictionary class]]) {
                [arr addObject:d];
            }else{
            NSDictionary *dic=((NSData*)d).mj_JSONObject;
            [arr addObject:dic];
            }
        }
        saveStr=arr.mj_JSONString;
        
    }
    else{
        NSDictionary *dic=[NSDictionary new];
        if ([object isKindOfClass:[NSDictionary class]]) {
            dic = object;
        }else{
            dic=((NSData*)object).mj_JSONObject;//[WJCModel2Json getObjectData:object];
        }
        saveStr=dic.mj_JSONString;//[FCModel2Json getJSON2Dic:dic];
    }
    [saveStr writeToFile:documentsPath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}
+(void)removeLocalWithClass:(Class)saveClass{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=NSStringFromClass(saveClass);
    if (saveName) {
        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    }
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    NSError *error = [NSError new];
    [fileMgr removeItemAtPath:documentsPath error:&error];
//    [saveStr writeToFile:documentsPath atomically:YES encoding:NSUTF8StringEncoding error:nil];;
}

+(id)getLocalWithClass:(Class)saveClass{
    NSString *saveName=NSStringFromClass(saveClass);
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    if (saveName) {
        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
   
        
        NSData *data=[NSData dataWithContentsOfFile:documentsPath];
    if (data.length>0) {
        id object=[[saveClass alloc]init];
        id decodeObj=[NSDictionary getDicWithData:data];

        if([decodeObj isKindOfClass:[NSArray class]]){
            id returnSave=[saveClass mj_objectArrayWithKeyValuesArray:decodeObj];
            return returnSave;
        }
       else if([decodeObj isKindOfClass:[NSDictionary class]]){
           if(decodeObj[@"Id"]){
           [decodeObj setValue:decodeObj[@"Id"] forKey:@"id"];
           }
            id returnSave=[saveClass mj_objectWithKeyValues:decodeObj];
            return returnSave;
            
        }
        id returnSave=[object setKVCWithObj:decodeObj];
        return returnSave;
    }
         }
    return nil;
}
+(void)saveLocalDataWithName:(NSString*)name andObject:(NSData*)object{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=name;
    if (saveName) {
        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    }
    [object writeToFile:documentsPath atomically:YES];
}
+(NSData*)getLocalDataWithName:(NSString*)name{
    NSString *saveName=name;
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
        documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
   
        
        NSData *data=[NSData dataWithContentsOfFile:documentsPath];

    return data;
}
+(void)saveSandBoxWithDic:(NSDictionary *)dic{
    NSUserDefaults *defaultUser=[NSUserDefaults standardUserDefaults];
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if (obj&&![obj isEqual:[NSNull null]]) {
             [defaultUser setObject:obj forKey:key];
        }
       
    }];
}
+(id)getSandBoxWithKey:(NSString *)key{
     NSUserDefaults *defaultUser=[NSUserDefaults standardUserDefaults];
    return [defaultUser objectForKey:key];
}
+(void)saveDataBaseClass:(Class)saveClass andObject:(id)object orType:(NSString *)type andOther:(NSString *)other{
    [saveSandBox createTableWithTableViewName:saveClass];
    if ([object isKindOfClass:[NSArray class]]) {
        for (id d in object) {
            if ([d isKindOfClass:[NSDictionary class]]) {
                [saveSandBox insertDataWithDic:d andClass:saveClass orType:type andOther:other];
            }else{
                NSDictionary *dic=((NSData*)object).mj_JSONObject;//object.mj_JSONObject;
                 [saveSandBox insertDataWithDic:dic andClass:saveClass orType:type andOther:other];
            }
        }
        
    }
    else{
        NSDictionary *dic=[NSDictionary new];
        if ([object isKindOfClass:[NSDictionary class]]) {
            dic = [NSDictionary dictionaryWithDictionary:object];
        }else{
            dic=((NSData*)object).mj_JSONObject;//object.mj_JSONObject;
        }
        [saveSandBox insertDataWithDic:dic andClass:saveClass orType:type andOther:other];
    }
}
+(void)DELETEDataWithType:(NSString*)type andOther:(NSString *)other andClass:(__unsafe_unretained Class)saveClass{
    
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
        //1.创建数据库(文件)
    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAME];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    char *errmsg="数据库错误";
    NSString *updateCode=[NSString stringWithFormat:@"delete from %@ where %@ and %@",  NSStringFromClass(saveClass),type?[NSString stringWithFormat:@"type='%@'",type]:@"1=1", other?[NSString stringWithFormat:@"other='%@'",[other stringByReplacingOccurrencesOfString:@"'" withString:@"’"]]:@"1=1"];
    if (!type&&!other) {
         NSString *updateCode=[NSString stringWithFormat:@"delete from %@",  NSStringFromClass(saveClass)];
    }
    ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
    NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
    if ([errStr containsString:@"no such table"]) {
        [self createTableWithTableViewName:saveClass];
    }
}
+(void)insertDataWithDic:(NSDictionary *)content andClass:(Class)saveClass orType:(NSString*)type andOther:(NSString *)other{
    NSString *ID=[NSString string];
    if (content[@"Id"]) {
       ID=content[@"Id"];
    }else if(content[@"id"]){
         ID=content[@"id"];
    }
    NSArray *row=[self getDataBaseWithClass:saveClass andLimitType:[NSString stringWithFormat:@"Id='%@' %@ %@",ID,type?[NSString stringWithFormat:@"and type= '%@'",type]:@"",other?[NSString stringWithFormat:@"and other= '%@'",other]:@""]];;
    if(row.count<1){
        NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAME];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg="数据库错误";
//        if (type &&((NSArray*)[saveSandBox getDataBaseWithClass:saveClass andLimitType:type]).count>0) {
//            [saveSandBox updateDataWithDic:content andClass:saveClass orType:type];
//        }else{
        NSString *str=content.printfJson;
        str=[str stringByReplacingOccurrencesOfString:@"'" withString:@"’"];
        NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
        NSString *updateCode=[NSString stringWithFormat:@"insert into %@ (id,data,meId,type,other) values ('%@','%@','%@','%@','%@')",  NSStringFromClass(saveClass),ID?ID:@"",text,[self getSandBoxWithKey:@"Id"]?[self getSandBoxWithKey:@"Id"]:@"",type?type:@"",other?other:@""];
        ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
        sqlite3_close(db);
        NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
        if ([errStr containsString:@"no such table"]) {
            [self createTableWithTableViewName:saveClass];
            [self insertDataWithDic:content andClass:saveClass orType:type andOther:other];
        }
//        }
            //    WJCLog(@"%s---%@",errmsg,updateCode);
    }else{
        [saveSandBox updateDataWithDic:content andClass:saveClass orType:type andOther:other];
    }
    
}
+(void)updateDataWithDic:(NSDictionary *)content andClass:(Class)saveClass orType:(NSString*)type andOther:(NSString *)other{
    NSString *ID=[NSString string];
    if (content[@"Id"]) {
        ID=content[@"Id"];
    }else if(content[@"id"]){
        ID=content[@"id"];
    }
        
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAME];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg="数据库错误";
    NSString *str=content.printfJson; //[FCModel2Json getJSON2Dic:content];
   str= [str stringByReplacingOccurrencesOfString:@"'" withString:@"’"];
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
        NSString *updateCode=[NSString stringWithFormat:@"update %@  set  data='%@'  where %@ and %@ and %@ and meId='%@'",  NSStringFromClass(saveClass),text,ID?[NSString stringWithFormat:@"Id='%@'",ID]:@"1=1",type?[NSString stringWithFormat:@"type='%@'",type]:@"1=1",other?[NSString stringWithFormat:@"other='%@'",other]:@"1=1",[self getSandBoxWithKey:@"Id"]];
        ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
        sqlite3_close(db);
        NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
        if ([errStr containsString:@"no such table"]) {
            [self createTableWithTableViewName:saveClass];
            [self insertDataWithDic:content andClass:saveClass orType:type andOther:other];
        }
}
+(id)getDataBaseWithClass:(Class)saveClass andLimitType:(NSString *)limitType{
    if (!saveClass) { //如果不需要传类名的，直接获取数据
        return nil;
        
    }
    NSMutableDictionary *selectResult;
        //对数据库sqlLite进行增删查改
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
        //1.创建数据库(文件)
    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAME];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    sqlite3_stmt *stmt;
    NSMutableArray *mutearr=[NSMutableArray new];
    NSString *str=[NSString stringWithFormat:@"select * from %@ where %@ and meId='%@' ORDER BY countId desc %@", NSStringFromClass(saveClass),!limitType?@"1=1":limitType,[self getSandBoxWithKey:@"Id"]?[self getSandBoxWithKey:@"Id"]:@"",limitType?@"":@"limit 199"];
    ret= sqlite3_prepare(db, [str cStringUsingEncoding:NSUTF8StringEncoding], -1/*sql字符串长度*/, &stmt/*查询返回结果*/, NULL);
    if (ret==SQLITE_OK) {
            //查询成功
        while (sqlite3_step(stmt)==SQLITE_ROW) {
            selectResult=[NSMutableDictionary dictionary];
            if (sqlite3_column_count(stmt)==2) {
                NSString *str=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
                NSError *error=[[NSError alloc]init];
                NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                
                if (!error) {
                    
                    @try {
                        id  result;
                        id object=[[saveClass alloc]init];
                        if ([dic isKindOfClass:[NSArray class]]) {
                            result=[saveClass mj_objectArrayWithKeyValuesArray:dic];
                            
                        }else if([dic isKindOfClass:[NSDictionary class]]){
                            result=[saveClass mj_objectWithKeyValues:dic];
                        }else{
                      result =[object setKVCWithObj:dic];
                        }
                        sqlite3_finalize(stmt);
                        sqlite3_close(db);
                        return result;
                    } @catch (NSException *exception) {
                        WJCLog(@"ex:%@",exception);
                        sqlite3_finalize(stmt);
                        sqlite3_close(db);
                        return nil;
                    }
                }
                
            }
            for (int i=0; i<sqlite3_column_count(stmt); i++) {
                NSString *str=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
                NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                
                str = [[temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                 str = [str stringByReplacingOccurrencesOfString:@"\r" withString:@""];
                str = [str stringByReplacingOccurrencesOfString:@"\t" withString:@""];
                str = [str stringByReplacingOccurrencesOfString:@" " withString:@""];
                NSString *r = str;
//                while (1) {
//
//                    NSRange beginRange = [r rangeOfString:@"\"{\""];
//                    NSRange endRange = [r rangeOfString:@"\"}\""];
//                    if(beginRange.location == NSNotFound){
//                        beginRange = [str rangeOfString:r];
//                        endRange.location =beginRange.location+ endRange.location;
//                        if ([str isEqual:r]) {
//                            break;
//                        }
//                        r = str;
//                    }else{
//                          r = [r substringFromIndex:beginRange.location+1];
//                        continue;
//                    }
//
//                    if (beginRange.location == NSNotFound||beginRange.location>endRange.location) {
//                        break;
//                    }
//                    NSString * replaceStr = [[str substringWithRange:NSMakeRange(beginRange.location+1, endRange.location+1-beginRange.location)] stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
//                    if (!replaceStr) {
//                                           break;
//                                       }
//                                           str = [str stringByReplacingCharactersInRange:NSMakeRange(beginRange.location+1, endRange.location+1-beginRange.location) withString:replaceStr];
//                     r = str;
//                }
                
                if (str.length>1) {
                    
                    if([[str substringToIndex:1] isEqualToString:@"["]&&[[str substringFromIndex:str.length-1 ] isEqualToString:@"]"]){
                        NSError *error=[[NSError alloc]init];
                        NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
                        NSArray *arr=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        
                        if (!error) {
                            if (!saveClass||[NSStringFromClass(saveClass) isEqual:@"NSArray"]||[NSStringFromClass(saveClass) isEqual:@"NSMutableArray"]) { //如果不需要传类名的，直接获取数据
                                [mutearr addObject:arr];
                                continue;
                            }
                                @try {
                                    
                                    NSArray *result=[saveClass mj_objectArrayWithKeyValuesArray:arr];;
                                    [mutearr addObjectsFromArray:result];
                                } @catch (NSException *exception) {
                                    WJCLog(@"ex:%@",exception);
                                } @finally {
                                    continue;
                                }
                        }
                    }
                    else if([[str substringToIndex:1] isEqualToString:@"{"]){
                        NSError *error;
                        NSData *data=[str.mj_JSONString dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        
                        if (!error) {
                            if (!saveClass||[NSStringFromClass(saveClass) isEqual:@"NSDictionary"]||[NSStringFromClass(saveClass) isEqual:@"NSMutableDictionary"]) { //如果不需要传类名的，直接获取数据
                                [mutearr addObject:dic];
                                continue;
                            }
                            @try {
                                
                                id object=[[saveClass alloc]init];
                                NSDictionary *result=[saveClass mj_objectWithKeyValues:dic];
                                [mutearr addObject:result];
                            } @catch (NSException *exception) {
                                WJCLog(@"ex:%@",exception);
                            } @finally {
                                continue;
                            }
                        }else{
//                            WJCLog(@"打印- %@",str);
                            sqlite3_finalize(stmt);
                            sqlite3_close(db);
                            
                            return @[saveClass?[[saveClass alloc]init]:@{@"error":error}];
                        }
                    }
                }
            }
        }
            //查询完后释放掉查询结果
        sqlite3_finalize(stmt);
    }
    
    sqlite3_close(db);
    return [[mutearr reverseObjectEnumerator] allObjects];
}
+(void)createTableWithTableViewName:(Class)saveClass{
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];//[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSArray *arr=@[@"Id",@"data",@"meId"];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAME];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg=nil;
        NSMutableString *str=[NSMutableString new];
        [str appendFormat:@"create table if not exists %@ (",NSStringFromClass(saveClass)];
        for (NSString *columnName in arr) {
            [str appendFormat:@"%@ text NULL DEFAULT '',",columnName];
        }
        str =[[str substringToIndex:str.length -1] mutableCopy];
        [str appendString:@",[countId] integer PRIMARY KEY autoincrement,[type] text NULL DEFAULT '',[other] text NULL DEFAULT '')"];
        
        @try {
            sqlite3_exec(db, [str cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, &errmsg);
            if (!errmsg) {
            }
            else{
                WJCLog(@"%s",errmsg);
                sqlite3_close(db);
                return;
            }
        } @catch (NSException *exception) {
            WJCLog(@"%@",exception);
        } @finally {
            sqlite3_close(db);
        }
        
    }
+(void)saveCookieWithCookie:(NSHTTPCookieStorage*)storage{
    if (!storage) {
        storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    }
    NSMutableArray *cookies = storage.cookies.mutableCopy;
    for (NSHTTPCookie *cookie  in cookies) {
        if ([cookie.name isEqual:@"JSESSIONID"]) {
            NSHTTPCookie *cok = [NSHTTPCookie cookieWithProperties:@{NSHTTPCookieName:@"shop_cookies",
                                       NSHTTPCookieValue:cookie.value}];
            [cookies addObject:cok];
        
            break;
        }
    }
   
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=@"FCHTTPCookies";
    documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    [data writeToFile:documentsPath atomically:YES];
    
//    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//    [userDefaults setObject:data forKey:@"FCHTTPcookie"];
    
}
//FC.Platform.CurrIdentityId当前身份id FC.Platform.Auth当前cookie  FC.Platform.CurrCategoryId当前供应链类别
+(void)addCookieWithCookie:(NSHTTPCookieStorage *)storage{
    NSArray *arrCookie=storage.cookies;
    NSMutableArray *set=[[saveSandBox getCookie] mutableCopy];
    if (!set) {
        set=[NSMutableArray new];
    }
    BOOL haveCookie=NO;
    for (NSHTTPCookie *cookie in arrCookie) {
        for (int i = 0; i<set.count; i++) {
            if ([cookie.name isEqual:((NSHTTPCookie*)set[i]).name]) {
                [set replaceObjectAtIndex:i withObject:cookie];
                haveCookie=YES;
            }
        }
        if (!haveCookie) {
             [set addObject:cookie];
        }
       haveCookie=NO;
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:set];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=@"FCHTTPCookies";
    documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    [data writeToFile:documentsPath atomically:YES];
}

+(void)addoneCookie:(NSHTTPCookie *)cookie{
    NSMutableArray *set=[[saveSandBox getCookie] mutableCopy];
    if (!set) {
        set=[NSMutableArray new];
    }
    BOOL haveCookie=NO;
        for (int i = 0; i<set.count; i++) {
            if ([cookie.name isEqual:((NSHTTPCookie*)set[i]).name]) {
                [set replaceObjectAtIndex:i withObject:cookie];
                haveCookie=YES;
            }
        }
        if (!haveCookie) {
             [set addObject:cookie];
       haveCookie=NO;
    }
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:set];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=@"FCHTTPCookies";
    documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    [data writeToFile:documentsPath atomically:YES];
}
+(NSArray <NSHTTPCookie*>*)getCookie{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=@"FCHTTPCookies";
    documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
    NSData *cookiesdata =[NSData dataWithContentsOfFile:documentsPath];// [data writeToFile:documentsPath atomically:YES];
//    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:@"FCHTTPcookie"];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
//        NSHTTPCookie *cookie;
//        for (cookie in cookies) {
//             [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
//
//        }
        return cookies;
    }
    return nil;
}
+(void)removeFilePath:(NSString*)path{
   [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
+(void)deleteCookies{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]) {

        [storage deleteCookie:cookie];
    }
//    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:storage.cookies];
//    [FCUserDefaults setObject:data forKey:@"FCHTTPcookie"];
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *saveName=@"FCHTTPCookies";
    documentsPath=[documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",saveName]];
   [[NSFileManager defaultManager] removeItemAtPath:documentsPath error:nil];
//    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
//        //1.创建数据库(文件)
//    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
//    [[NSFileManager defaultManager] removeItemAtPath:dbfilepath error:nil];
}
//删除本地数据
+(void)deleteAllObjectWithCookie:(BOOL)deleteCookie{
//    NSString *DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

//    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
//    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsPath];
//    for (NSString *fileName in enumerator) {
//        if([fileName containsString:@"FCHTTPCookies"]){
//             if (!deleteCookie) {
//                 continue;
//             }
//        }
//        if([fileName containsString:@"NIM"]){
//                continue;
//        }
//        if([fileName containsString:@"H5Config"]){
//                continue;
//        }
//        if([fileName containsString:@"webCache"]){
//            continue;
//        }
//        if([fileName containsString:@"FuChengCache"]){
//            continue;
//        }
//        [[NSFileManager defaultManager] removeItemAtPath:[documentsPath stringByAppendingPathComponent:fileName] error:nil];
//        }
    
    if (deleteCookie) {
        NSHTTPCookie *cookie;
        NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (cookie in [storage cookies]) {
            if ([cookie.name containsString:@"FC.Platform.CurrCategoryId"]) {
                continue;
            }
            [storage deleteCookie:cookie];
        }
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:storage.cookies];
        [FCUserDefaults setObject:data forKey:@"FCHTTPCookies"];
        [saveSandBox deleteCookies];
    }

    if ([NSClassFromString(@"FCWebViewController") respondsToSelector:NSSelectorFromString(@"downOrUpdateH5Config")]) {
           [NSClassFromString(@"FCWebViewController") performSelector:NSSelectorFromString(@"downOrUpdateH5Config")];
                          }
}
+(void)setCookie{
    [saveSandBox getCookie];
}
+ (NSDate *)currentTime
{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    NSDate *localDate = [date  dateByAddingTimeInterval:interval];
    return localDate;
}
static NSDictionary*APIFileDic;
+(NSString *)returnAPIWithName:(NSString *)str{

    return [WJCDeployModel getDeployWithStr:str];
//    }
}
-(void)deleteDefaultWithKey:(NSString *)key{
    [FCUserDefaults removeObjectForKey:key];
}
-(void)removeDocumentCache{
    [saveSandBox deleteAllObjectWithCookie:NO];
}
-(void)removeLibraryCache{
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:documentsPath];
    for (NSString *fileName in enumerator) {
        [[NSFileManager defaultManager] removeItemAtPath:[documentsPath stringByAppendingPathComponent:fileName] error:nil];
    }
}

+(void)createH5TableWithTableViewName:(Class)saveClass{
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSArray *arr=@[@"Id",@"data"];
        //1.创建数据库(文件)
    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    char *errmsg=nil;
    NSMutableString *str=[NSMutableString new];
    [str appendFormat:@"create table if not exists %@ (",NSStringFromClass(saveClass)];
    for (NSString *columnName in arr) {
        [str appendFormat:@"%@ text NULL DEFAULT '',",columnName];
    }
    str =[[str substringToIndex:str.length -1] mutableCopy];
    [str appendString:@",[countId] integer PRIMARY KEY autoincrement,[type] text NULL DEFAULT '',[other] text NULL DEFAULT '')"];
    
    @try {
        sqlite3_exec(db, [str cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, &errmsg);
        if (!errmsg) {
        }
        else WJCLog(@"%s",errmsg);
    } @catch (NSException *exception) {
        WJCLog(@"%@",exception);
    } @finally {
        sqlite3_close(db);
    }
    
}
+(void)saveH5DataBaseClass:(Class)saveClass andObject:(id)object orType:(NSString *)type andOther:(NSString *)other{
    [saveSandBox createTableWithTableViewName:saveClass];
    if ([object isKindOfClass:[NSArray class]]) {
        for (id d in object) {
            if ([d isKindOfClass:[NSDictionary class]]) {
                [saveSandBox insertH5DataWithDic:d andClass:saveClass orType:type andOther:other];
            }else{
                NSDictionary *dic=((NSData*)d).mj_JSONObject;
                 [saveSandBox insertH5DataWithDic:dic andClass:saveClass orType:type andOther:other];
            }
        }
        
    }
    else{
        NSDictionary *dic=[NSDictionary new];
        if ([object isKindOfClass:[NSDictionary class]]) {
            dic = [NSDictionary dictionaryWithDictionary:object];
        }else{
            dic=((NSData*)object).mj_JSONObject;
        }
        [saveSandBox insertH5DataWithDic:dic andClass:saveClass orType:type andOther:other];
    }
}
+(void)DELETEH5DataWithType:(NSString*)type andOther:(NSString *)other andClass:(__unsafe_unretained Class)saveClass{
    
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        //1.创建数据库(文件)
    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    char *errmsg="数据库错误";
    NSString *updateCode=[NSString stringWithFormat:@"delete from %@ where %@ and %@",  NSStringFromClass(saveClass),type?[NSString stringWithFormat:@"type='%@'",type]:@"1=1", other?[NSString stringWithFormat:@"other='%@'",[other stringByReplacingOccurrencesOfString:@"'" withString:@"’"]]:@"1=1"];
    if (!type&&!other) {
         NSString *updateCode=[NSString stringWithFormat:@"delete from %@",  NSStringFromClass(saveClass)];
    }
    ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
    sqlite3_close(db);
    NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
    if ([errStr containsString:@"no such table"]) {
        [self createTableWithTableViewName:saveClass];
    }
sqlite3_close(db);
}
+(void)insertH5DataWithDic:(NSDictionary *)content andClass:(Class)saveClass orType:(NSString*)type andOther:(NSString *)other{
    NSString *ID=[NSString string];
    if (content[@"Id"]) {
       ID=content[@"Id"];
    }else if(content[@"id"]){
         ID=content[@"id"];
    }
    NSArray *row=[self getH5DataBaseWithClass:saveClass andLimitType:[NSString stringWithFormat:@"Id='%@' %@ %@",ID,type?[NSString stringWithFormat:@"and type= '%@'",type]:@"",other?[NSString stringWithFormat:@"and other= '%@'",other]:@""]];;
    if(row.count<1){
        
        NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg="数据库错误";
//        if (type &&((NSArray*)[saveSandBox getDataBaseWithClass:saveClass andLimitType:type]).count>0) {
//            [saveSandBox updateDataWithDic:content andClass:saveClass orType:type];
//        }else{
        NSString *str=content.printfJson;
        str=[str stringByReplacingOccurrencesOfString:@"'" withString:@"’"];
        NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
        NSString *updateCode=[NSString stringWithFormat:@"insert into %@ (id,data,type,other) values ('%@','%@','%@','%@')",  NSStringFromClass(saveClass),ID?ID:@"",text,type?type:@"",other?other:@""];
        ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
        sqlite3_close(db);
        NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
        if ([errStr containsString:@"no such table"]) {
            [self createTableWithTableViewName:saveClass];
            [self insertH5DataWithDic:content andClass:saveClass orType:type andOther:other];
        }
//        }
            //    WJCLog(@"%s---%@",errmsg,updateCode);
    }else{
        [saveSandBox updateH5DataWithDic:content andClass:saveClass orType:type andOther:other];
    }
    
}
+(void)updateH5DataWithDic:(NSDictionary *)content andClass:(Class)saveClass orType:(NSString*)type andOther:(NSString *)other{
    NSString *ID=[NSString string];
    if (content[@"Id"]) {
        ID=content[@"Id"];
    }else if(content[@"id"]){
        ID=content[@"id"];
    }
        
        NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg="数据库错误";
        NSString *str=content.printfJson;
   str= [str stringByReplacingOccurrencesOfString:@"'" withString:@"’"];
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
        NSString *updateCode=[NSString stringWithFormat:@"update %@  set  data='%@'  where %@ and %@ and %@",  NSStringFromClass(saveClass),text,ID?[NSString stringWithFormat:@"Id='%@'",ID]:@"1=1",type?[NSString stringWithFormat:@"type='%@'",type]:@"1=1",other?[NSString stringWithFormat:@"other='%@'",other]:@"1=1"];
        ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
        sqlite3_close(db);
        NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
        if ([errStr containsString:@"no such table"]) {
            [self createTableWithTableViewName:saveClass];
            [self insertH5DataWithDic:content andClass:saveClass orType:type andOther:other];
        }
}
+(id)getH5DataBaseWithClass:(Class)saveClass andLimitType:(NSString *)limitType{
    if (!saveClass) { //如果不需要传类名的，直接获取数据
        return nil;
        
    }
    NSMutableDictionary *selectResult;
        //对数据库sqlLite进行增删查改
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
        //1.创建数据库(文件)
    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:SQLNAMEH5];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    sqlite3_stmt *stmt;
    NSMutableArray *mutearr=[NSMutableArray new];
    NSString *str=[NSString stringWithFormat:@"select * from %@ where %@ ORDER BY countId desc %@", NSStringFromClass(saveClass),!limitType?@"1=1":limitType,limitType?@"":@"limit 99"];
    ret= sqlite3_prepare(db, [str cStringUsingEncoding:NSUTF8StringEncoding], -1/*sql字符串长度*/, &stmt/*查询返回结果*/, NULL);
    if (ret==SQLITE_OK) {
            //查询成功
        while (sqlite3_step(stmt)==SQLITE_ROW) {
            selectResult=[NSMutableDictionary dictionary];
            if (sqlite3_column_count(stmt)==2) {
                NSString *str=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
                NSError *error=[[NSError alloc]init];
                NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                
                if (!error) {
                    
                    @try {
                        id  result;
                        id object=[[saveClass alloc]init];
                        if ([dic isKindOfClass:[NSArray class]]) {
                            result=[saveClass mj_objectArrayWithKeyValuesArray:dic];
                            
                        }else if([dic isKindOfClass:[NSDictionary class]]){
                            result=[saveClass mj_objectWithKeyValues:dic];
                        }else{
                      result =[object setKVCWithObj:dic];
                        }
                        return result;
                    } @catch (NSException *exception) {
                        WJCLog(@"ex:%@",exception);
                        return nil;
                    }
                }
                
            }
            for (int i=0; i<sqlite3_column_count(stmt); i++) {
                NSString *str=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
                NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
                
                str = [[temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]] stringByReplacingOccurrencesOfString:@"\n" withString:@""];
                if (str.length>1) {
                    
                    if([[str substringToIndex:1] isEqualToString:@"["]&&[[str substringFromIndex:str.length-1 ] isEqualToString:@"]"]){
                        NSError *error=[[NSError alloc]init];
                        NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
                        NSArray *arr=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        
                        if (!error) {
                            if (!saveClass||[NSStringFromClass(saveClass) isEqual:@"NSArray"]||[NSStringFromClass(saveClass) isEqual:@"NSMutableArray"]) { //如果不需要传类名的，直接获取数据
                                [mutearr addObject:arr];
                                continue;
                            }
                                @try {
                                    
                                    NSArray *result=[saveClass mj_objectArrayWithKeyValuesArray:arr];;
                                    [mutearr addObjectsFromArray:result];
                                } @catch (NSException *exception) {
                                    WJCLog(@"ex:%@",exception);
                                } @finally {
                                    continue;
                                }
                        }
                    }
                    else if([[str substringToIndex:1] isEqualToString:@"{"]){
                        NSError *error;
                        NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
                        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
                        
                        if (!error) {
                            if (!saveClass||[NSStringFromClass(saveClass) isEqual:@"NSDictionary"]||[NSStringFromClass(saveClass) isEqual:@"NSMutableDictionary"]) { //如果不需要传类名的，直接获取数据
                                [mutearr addObject:dic];
                                continue;
                            }
                            @try {
                                
                                id object=[[saveClass alloc]init];
                                NSDictionary *result=[saveClass mj_objectWithKeyValues:dic];
                                [mutearr addObject:result];
                            } @catch (NSException *exception) {
                                WJCLog(@"ex:%@",exception);
                            } @finally {
                                continue;
                            }
                        }
                        
                    }
                }
            }
        }
            //查询完后释放掉查询结果
        sqlite3_finalize(stmt);
    }
    
    sqlite3_close(db);
    return [[mutearr reverseObjectEnumerator] allObjects];
}
+(NSString*)getCurrentEnvironment{
    NSString *str = [FCUserDefaults objectForKey:@"currVersion"];
    return str;
}
+(NSString*)getCurrentVersion{
   
    return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}
NSString * const KEY_UDID_INSTEAD = @"com.myapp.udid.test";
+(NSString *)getDeviceIDInKeychain {
    NSString *getUDIDInKeychain = (NSString *)[saveSandBox load:KEY_UDID_INSTEAD];
    if (!getUDIDInKeychain ||[getUDIDInKeychain isEqualToString:@""]||[getUDIDInKeychain isKindOfClass:[NSNull class]]) {
        CFUUIDRef puuid = CFUUIDCreate( nil );
        CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
        NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
        CFRelease(puuid);
        CFRelease(uuidString);
        [saveSandBox save:KEY_UDID_INSTEAD data:result];
        getUDIDInKeychain = (NSString *)[saveSandBox load:KEY_UDID_INSTEAD];
    }
    WJCLog(@"最终 ———— UDID_INSTEAD %@",getUDIDInKeychain);
    return getUDIDInKeychain;
}
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    //Since in our simple case we are expecting only a single attribute to be returned (the password) we can set the attribute kSecReturnData to kCFBooleanTrue
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(id)kSecReturnData];
    [keychainQuery setObject:(id)kSecMatchLimitOne forKey:(id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    if (keyData)
        CFRelease(keyData);
    return ret;
}
+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (id)kSecClassGenericPassword,(id)kSecClass,
            service, (id)kSecAttrService,
            service, (id)kSecAttrAccount,
            (id)kSecAttrAccessibleAfterFirstUnlock,(id)kSecAttrAccessible,
            nil];
}
+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((CFDictionaryRef)keychainQuery, NULL);
}

///. 清除缓存
+ (void)clearSandBoxFile
{
    
    NSString * cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    NSArray * files = [[NSFileManager defaultManager ] subpathsAtPath :cachePath];
    //NSLog ( @"cachpath = %@" , cachePath);
    for ( NSString * p in files) {
        
        NSError * error = nil ;
        //获取文件全路径
        NSString * fileAbsolutePath = [cachePath stringByAppendingPathComponent :p];
        
        if ([[NSFileManager defaultManager ] fileExistsAtPath :fileAbsolutePath]) {
            [[NSFileManager defaultManager ] removeItemAtPath :fileAbsolutePath error :&error];
        }
    }
}

///获取缓存大小
+( float )getCacheSize
{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES) firstObject];
    return [ self folderSizeAtPath :cachePath];
}
// 遍历文件夹获得文件夹大小，返回多少 M
+ ( float ) folderSizeAtPath:( NSString *) folderPath{
    
    NSFileManager * manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath :folderPath]) return 0 ;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator];
    NSString * fileName;
    long long folderSize = 0 ;
    while ((fileName = [childFilesEnumerator nextObject]) != nil ){
        //获取文件全路径
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
        folderSize += [ self fileSizeAtPath :fileAbsolutePath];
    }

    return folderSize/( 1024.0 * 1024.0);
    
}



// 计算 单个文件的大小
+ ( long long ) fileSizeAtPath:( NSString *) filePath{
    NSFileManager * manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath :filePath]){
        return [[manager attributesOfItemAtPath :filePath error : nil] fileSize];
    }
    return 0;
}


/// 获取对象属性
/// @param saveClass 对象
/// @param re 是否返回属性类型是为返回属性类型,否为返回属性名称
+(NSMutableArray*)getAllPropertNameWithClass:(Class)saveClass returnClass:(BOOL)re{
    unsigned int outCount, i;
        // 获取对象里的属性列表
    objc_property_t * properties = class_copyPropertyList(saveClass , &outCount);
    NSMutableArray *arr = [NSMutableArray new];
    for (i = 0; i < outCount; i++) {
        
        objc_property_t property =properties[i];
            //  属性名转成字符串
        NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
        const char *objName = [NSObject getControllerIvalWithController:saveClass andPropertyName:propertyName];
        NSString *objNameStr=[NSString stringWithFormat:@"%s",objName];

        if (re) {
            [arr addObject:objNameStr];
        }else{
            [arr addObject:propertyName];
        }
    }
    free(properties);
    return arr;
}
///创建表
+(void)createNewDataBaseWithTableViewClass:(Class)saveClass{
    
    NSArray *property = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:NO];
    NSArray *propertyClass = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:YES];
    NSMutableArray *arr = [NSMutableArray new];
    for (int i = 0; i <propertyClass.count; i++) {
        NSString *propertyName = property[i];
        NSString *type = propertyClass[i];
     if (type.length==1||[type isEqual:@"NSMutableString"]||[type isEqual:@"NSString"]||[type isEqual:@"NSNumber"]) {
                    [arr addObject:propertyName];
                }else if([type isEqual:@"NSArray"]
                         ||[type isEqual:@"NSDictionary"]
                         ||[type isEqual:@"NSMutableDictionary"]
                         ||[type isEqual:@"NSMutableArray"]){
                    continue;
                }else{
                    [saveSandBox createNewDataBaseWithTableViewClass:NSClassFromString(type)];
                }
    }
    if(property.count>0){
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
    
//    NSArray *arr=@[@"Id",@"data",@"meId"];
            //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",[FCUserDefaults objectForKey:@"appCNName"]]];
            //参数一数据库所在路径//参数二给定数据库类型对象地址
        sqlite3 *db=NULL;
        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
        if (ret!=SQLITE_OK/*0为创建成功*/) {
            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
        }
        char *errmsg=nil;
        NSMutableString *str=[NSMutableString new];
        [str appendFormat:@"create table if not exists %@ (",NSStringFromClass(saveClass)];
        for (NSString *columnName in arr) {
            [str appendFormat:@"%@ text NULL DEFAULT '',",columnName];
        }
        str =[[str substringToIndex:str.length -1] mutableCopy];
        [str appendString:@",[countId] integer PRIMARY KEY autoincrement,[type] text NULL DEFAULT '',[other] text NULL DEFAULT '',[meId] text NULL DEFAULT '')"];
        
        @try {
            sqlite3_exec(db, [str cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, &errmsg);
            if (!errmsg) {
            }
            else{
                WJCLog(@"%s",errmsg);
                sqlite3_close(db);
                return;
            }
        } @catch (NSException *exception) {
            WJCLog(@"%@",exception);
        } @finally {
            sqlite3_close(db);
        }
    }
}
///增
+(void)insertNewDataBaseWithDic:(id)content andClass:(Class)saveClass orType:(NSString *)type andOther:(NSString *)other{
//    if (!content) {
//        return;
//    }
//    if ([content isKindOfClass:[NSArray class]]) {
//        for (id co in content) {
//            [saveSandBox updateNewDataBaseWithDic:co andClass:saveClass orType:type andOther:other];
//
//        }
//        return;
//    }
//
//    NSMutableArray *property = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:NO].mutableCopy;
//    NSMutableArray *propertyArr = [NSMutableArray new];
//    NSMutableArray *propertyClass = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:YES].mutableCopy;
//    NSMutableArray *contentArr = [NSMutableArray new];
//    for (int i = 0; i <propertyClass.count; i++) {
//        NSString *typeStr = propertyClass[i];
//     if (typeStr.length==1||[typeStr isEqual:@"NSMutableString"]||[typeStr isEqual:@"NSString"]||[typeStr isEqual:@"NSNumber"]
//         ||[typeStr isEqual:@"NSDictionary"]
//         ||[typeStr isEqual:@"NSMutableDictionary"]) {
//         [contentArr addObject:[NSString stringWithFormat:@"'%@'",[content valueForKey:property[i]]?[content valueForKey:property[i]]:@""]];
//         [propertyArr addObject:[NSString stringWithFormat:@"'%@'",property[i]]];
//                }else if([typeStr isEqual:@"NSArray"]
//                         ||[typeStr isEqual:@"NSMutableArray"]){
//                    if ([[content class] respondsToSelector:NSSelectorFromString(@"mj_objectClassInArray")]) {
//                        [self updateNewDataBaseWithDic:[content valueForKey:property[i]] andClass:[[[content class] mj_objectClassInArray][property[i]] isKindOfClass:[NSString class]]?NSClassFromString([[content class] mj_objectClassInArray][property[i]]):[[content class] mj_objectClassInArray][property[i]] orType:type andOther:other];
//                        [property removeObjectAtIndex:i];
//                        [propertyClass removeObjectAtIndex:i];
//                        i--;
//                    }else{
//                        [propertyArr addObject:[NSString stringWithFormat:@"'%@'",property[i]]];
//                        [contentArr addObject:[NSString stringWithFormat:@"'%@'",[content valueForKey:property[i]]?[content valueForKey:property[i]]:@""]];
//                    }
//                }else{
//                    if([content valueForKey:property[i]]){
//                    [self updateNewDataBaseWithDic:[content valueForKey:property[i]] andClass:[[content valueForKey:property[i]] class] orType:type andOther:other];
//                    [property removeObjectAtIndex:i];
//                    [propertyClass removeObjectAtIndex:i];
//                    i--;
//                    }
//                }
//    }
//
//    if([self getSandBoxWithKey:@"Id"]){
//        [propertyArr addObject:@"meId"];
//        [contentArr addObject:[NSString stringWithFormat:@"'%@'",[self getSandBoxWithKey:@"Id"]]];
//    }
//    if (saveClass) {
//    NSString *updateCode=[NSString stringWithFormat:@"insert into %@ (%@) values (%@)",  NSStringFromClass(saveClass),[propertyArr componentsJoinedByString:@","],[contentArr componentsJoinedByString:@","]];
//    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
//        //1.创建数据库(文件)
//    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",[FCUserDefaults objectForKey:@"appCNName"]]];
//        //参数一数据库所在路径//参数二给定数据库类型对象地址
//    sqlite3 *db=NULL;
//    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
//    if (ret!=SQLITE_OK/*0为创建成功*/) {
//        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
//    }
//    char *errmsg="数据库错误";
//    ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
//    sqlite3_close(db);
//    NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
//    if ([errStr containsString:@"no such table"]) {
//        [self createNewDataBaseWithTableViewClass:saveClass];
//        [self insertNewDataBaseWithDic:content andClass:saveClass orType:type andOther:other];
//    }
//    }
}
///改
+(void)updateNewDataBaseWithDic:(id)content andClass:(Class)saveClass orType:(NSString *)type andOther:(NSString *)other{
    
//        if (!content) {
//            return;
//        }
//        if ([content isKindOfClass:[NSArray class]]) {
//            for (id co in content) {
//                [saveSandBox updateNewDataBaseWithDic:co andClass:saveClass orType:type andOther:other];
//            }
//            return;
//        }
//        NSMutableArray *property = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:NO].mutableCopy;
//        NSMutableArray *propertyClass = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:YES].mutableCopy;
//        NSMutableArray *contentArr = [NSMutableArray new];
//        NSMutableArray *typeArr = [NSMutableArray new];
//        for (int i = 0; i <propertyClass.count; i++) {
//            NSString *typeStr = propertyClass[i];
//            if ([(NSString*)property[i] containsString:@"Id"]) {
//                if (typeStr.length>1&&[(NSString*)[content valueForKey:property[i]] length]>0) {
//
//                    [typeArr addObject:[NSString stringWithFormat:@"[%@] = '%@'",property[i],[content valueForKey:property[i]]]];
//                }
//
//            }
//         if (typeStr.length==1||[typeStr isEqual:@"NSMutableString"]||[typeStr isEqual:@"NSString"]||[typeStr isEqual:@"NSNumber"]
//             ||[typeStr isEqual:@"NSDictionary"]
//             ||[typeStr isEqual:@"NSMutableDictionary"]) {
//             [contentArr addObject:[NSString stringWithFormat:@"%@ = '%@'",property[i],[content valueForKey:property[i]]?[content valueForKey:property[i]]:@""]];
//                    }else if([typeStr isEqual:@"NSArray"]
//                             ||[typeStr isEqual:@"NSMutableArray"]){
//                        if ([[content class] respondsToSelector:NSSelectorFromString(@"mj_objectClassInArray")]) {
//                            [self updateNewDataBaseWithDic:[content valueForKey:property[i]] andClass:[[[content class] mj_objectClassInArray][property[i]] isKindOfClass:[NSString class]]?NSClassFromString([[content class] mj_objectClassInArray][property[i]]):[[content class] mj_objectClassInArray][property[i]] orType:type andOther:other];
//                        [property removeObjectAtIndex:i];
//                        [propertyClass removeObjectAtIndex:i];
//                        i--;
//                        }else{
//                            [contentArr addObject:[NSString stringWithFormat:@"%@ = '%@'",property[i],[content valueForKey:property[i]]?[content valueForKey:property[i]]:@""]];
//                        }
//                    }else{
//                        [self updateNewDataBaseWithDic:[content valueForKey:property[i]] andClass:NSClassFromString(typeStr) orType:type andOther:other];
//                        [property removeObjectAtIndex:i];
//                        [propertyClass removeObjectAtIndex:i];
//                        i--;
//                    }
//        }
//    if([saveSandBox getNewDataBaseWithClass:saveClass andLimitType:[typeArr componentsJoinedByString:@" and "] andGetSub:NO].count>0) {
//        NSString *updateCode=[NSString stringWithFormat:@"update %@  set  %@  where %@ and %@",  NSStringFromClass(saveClass),[contentArr componentsJoinedByString:@" ,"],typeArr.count>0?[typeArr componentsJoinedByString:@" and "]:@"1=1",other?[NSString stringWithFormat:@"other='%@'",other]:@"1=1"];
//        NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
//            //1.创建数据库(文件)
//        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",[FCUserDefaults objectForKey:@"appCNName"]]];
//            //参数一数据库所在路径//参数二给定数据库类型对象地址
//        sqlite3 *db=NULL;
//        int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
//        if (ret!=SQLITE_OK/*0为创建成功*/) {
//            WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
//        }
//        char *errmsg="数据库错误";
//        ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
//        sqlite3_close(db);
//        NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
//        if ([errStr containsString:@"no such table"]) {
//            [self createNewDataBaseWithTableViewClass:saveClass];
//            [self insertNewDataBaseWithDic:content andClass:saveClass orType:[typeArr componentsJoinedByString:@" and "] andOther:other];
//        }
//
//    }else{
//        [saveSandBox insertNewDataBaseWithDic:content andClass:saveClass orType:[typeArr componentsJoinedByString:@" and "] andOther:other];
//    }
}
///查
+(NSArray*)getNewDataBaseWithClass:(Class)saveClass andLimitType:(NSString *)limitType andGetSub:(BOOL)getSub{
    return  nil;
//    if (!saveClass) { //如果不需要传类名的，直接获取数据
//        return nil;
//
//    }
//        //对数据库sqlLite进行增删查改
//    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
//        //1.创建数据库(文件)
//    NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",[FCUserDefaults objectForKey:@"appCNName"]]];
//        //参数一数据库所在路径//参数二给定数据库类型对象地址
//    sqlite3 *db=NULL;
//    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
//    if (ret!=SQLITE_OK/*0为创建成功*/) {
//        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
//    }
//    sqlite3_stmt *stmt;
//    NSMutableArray *mutearr=[NSMutableArray new];
//
//    NSString *str=[NSString stringWithFormat:@"select * from %@ where %@ and meId='%@' ORDER BY countId desc %@", NSStringFromClass(saveClass),limitType.length>0?limitType
//                                            :@"1=1",[self getSandBoxWithKey:@"Id"]?[self getSandBoxWithKey:@"Id"]:@"",limitType?@"":@"limit 999"];
//    ret= sqlite3_prepare(db, [str cStringUsingEncoding:NSUTF8StringEncoding], -1/*sql字符串长度*/, &stmt/*查询返回结果*/, NULL);
//    if (ret==SQLITE_OK) {
//            //查询成功
//
//        while (sqlite3_step(stmt)==SQLITE_ROW) {
//            NSMutableDictionary *selectResult=[NSMutableDictionary dictionary];
//
//            for (int i=0; i<sqlite3_column_count(stmt); i++) {
//                NSString *str=[NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, i)];
//
//                NSString *columnNamestr=[NSString stringWithUTF8String:(char *)sqlite3_column_name(stmt, i)];
//                [selectResult setValue:str forKey:columnNamestr];
//            }
//            id obj = [saveClass mj_objectWithKeyValues:selectResult];
//            if (getSub) {
//                NSMutableArray *property = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:NO].mutableCopy;
//                NSMutableArray *propertyClass = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:YES].mutableCopy;
//                for (int i = 0; i <propertyClass.count; i++) {
//                    NSString *type = propertyClass[i];
//                 if (type.length==1||[type isEqual:@"NSMutableString"]||[type isEqual:@"NSString"]||[type isEqual:@"NSNumber"]||[type isEqual:@"NSDictionary"] ||[type isEqual:@"NSMutableDictionary"]) {
//                            }
//                 else if([type isEqual:@"NSArray"]
//                                     ||[type isEqual:@"NSMutableArray"]){
//                                if ([[obj class] respondsToSelector:NSSelectorFromString(@"mj_objectClassInArray")]) {
//                                    NSMutableArray *arr = [NSMutableArray new];
//                                    if ([[obj class] respondsToSelector:NSSelectorFromString(@"wjc_localDataBaseUnion")]) {
//                                        NSDictionary *dic =[[obj class] performSelector:NSSelectorFromString(@"wjc_localDataBaseUnion")];
//                                        for (NSString *str in dic) {
//                                            if ([dic[str] containsString:@"."]&&[dic[str] containsString:property[i]]) {
//                                                NSArray *mutableArr = [(NSString*)dic[str] componentsSeparatedByString:@"."];
//                                                [arr addObject:[NSString stringWithFormat:@"[%@]='%@'",mutableArr.lastObject,[obj valueForKey:str]]];
//                                            }
//                                        }
//
//                                    }
//                                    [obj setValue:[saveSandBox getNewDataBaseWithClass:[[[obj class] mj_objectClassInArray][property[i]] isKindOfClass:[NSString class]]?NSClassFromString([[obj class] mj_objectClassInArray][property[i]]):[[obj class] mj_objectClassInArray][property[i]] andLimitType:[arr componentsJoinedByString:@" and "] andGetSub:getSub] forKey:property[i]];
//                                }
//
//                            }else{
//                                NSMutableArray *arr = [NSMutableArray new];
//                                if ([[obj class] respondsToSelector:NSSelectorFromString(@"wjc_localDataBaseUnion")]) {
//                                    NSDictionary *dic =[[obj class] performSelector:NSSelectorFromString(@"wjc_localDataBaseUnion")];
//                                    for (NSString *str in dic) {
//                                        if ([dic[str] containsString:@"."]&&[dic[str] containsString:property[i]]) {
//                                            NSArray *mutableArr = [(NSString*)dic[str] componentsSeparatedByString:@"."];
//                                            [arr addObject:[NSString stringWithFormat:@"%@='%@'",mutableArr.lastObject,[obj valueForKey:str]]];
//                                        }
//                                    }
//
//                                }
//                                NSArray *a =[saveSandBox getNewDataBaseWithClass:NSClassFromString(type) andLimitType:arr.count>0 ?[arr componentsJoinedByString:@" and "]:@"1=1" andGetSub:getSub];
//                                if (a.count>0) {
//                                    if([type isEqual:@"NSArray"]
//                                                        ||[type isEqual:@"NSMutableArray"]){
//                                    [obj setValue:a forKey:property[i]];
//                                    }else{
//                                        [obj setValue:a[0] forKey:property[i]];
//                                    }
//                                }
//
//                            }
//                }
//            }
//
//            [mutearr addObject:obj];
//        }
//            //查询完后释放掉查询结果
//        sqlite3_finalize(stmt);
//    }
//
//    sqlite3_close(db);
//    return [[mutearr reverseObjectEnumerator] allObjects];
}
///删
+(void)DELETENewDataWithDic:(id)content andClass:(Class)saveClass{

  
        if (!content) {
//            NSString *updateCode=[NSString stringWithFormat:@"delete from %@",  NSStringFromClass(saveClass)];
            return;
        }
        if ([content isKindOfClass:[NSArray class]]) {
            for (id co in content) {
                [saveSandBox DELETENewDataWithDic:co andClass:saveClass];
            }
        }
        NSMutableArray *property = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:NO].mutableCopy;
        NSMutableArray *propertyClass = [saveSandBox getAllPropertNameWithClass:saveClass returnClass:YES].mutableCopy;
        NSMutableArray *typeArr = [NSMutableArray new];
        for (int i = 0; i <propertyClass.count; i++) {
            NSString *typeStr = propertyClass[i];
            if ([[(NSString*)property[i] lowercaseString] containsString:@"id"]) {
                [typeArr addObject:[NSString stringWithFormat:@"[%@]='%@'",property[i],[content valueForKey:property[i]]]];
            }
         if (typeStr.length==1||[typeStr isEqual:@"NSMutableString"]||[typeStr isEqual:@"NSString"]||[typeStr isEqual:@"NSNumber"]
             ||[typeStr isEqual:@"NSDictionary"]
             ||[typeStr isEqual:@"NSMutableDictionary"]) {
                    }else if([typeStr isEqual:@"NSArray"]
                             ||[typeStr isEqual:@"NSMutableArray"]){
                        if ([[content class] respondsToSelector:NSSelectorFromString(@"mj_objectClassInArray")]) {
                            [self DELETENewDataWithDic:[content valueForKey:property[i]] andClass:NSClassFromString(typeStr)];//insertNewDataBaseWithDic:[content valueForKey:property[i]] andClass:NSClassFromString(typeStr) orType:type andOther:other]
                        }
                    }
        }
    if([saveSandBox getNewDataBaseWithClass:saveClass andLimitType:[typeArr componentsJoinedByString:@" and "] andGetSub:YES].count>0) {
    NSString *documentSTR=[NSSearchPathForDirectoriesInDomains (NSCachesDirectory , NSUserDomainMask , YES ) firstObject];
        //1.创建数据库(文件)
        NSString *dbfilepath=[documentSTR  stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite",[FCUserDefaults objectForKey:@"appCNName"]]];
        //参数一数据库所在路径//参数二给定数据库类型对象地址
    sqlite3 *db=NULL;
    int ret= sqlite3_open([dbfilepath cStringUsingEncoding:NSUTF8StringEncoding]/*转成C语言类型*/, &db);
    if (ret!=SQLITE_OK/*0为创建成功*/) {
        WJCLog(@"创建失败:%s",sqlite3_errmsg(db));
    }
    char *errmsg="数据库错误";
    NSString *updateCode=[NSString stringWithFormat:@"delete from %@ where %@",  NSStringFromClass(saveClass),[typeArr componentsJoinedByString:@" and "]];

    ret= sqlite3_exec(db/*数据库名*/,[updateCode cStringUsingEncoding:NSUTF8StringEncoding]/*要执行的sql语句*/, NULL/*返回语句*/, NULL, &errmsg);
    NSString *errStr=[NSString stringWithFormat:@"%s",errmsg];
    if ([errStr containsString:@"no such table"]) {
        [self createNewDataBaseWithTableViewClass:saveClass];
    }
    }
}
@end
